import Axios, { IAxiosRequestConfig, IAxiosResponse, AxiosError } from './Axios'
import utils from '@/utils/index'
import { CacheEnum } from '@/enum/CacheEnum'
import { ErrMessageInfo } from '@/enum/httpEnum'
import { ElMessage } from 'element-plus'

const request = new Axios({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    Authorization: `Bearer ${utils.store.get(CacheEnum.TOKEN_NAME)}`,
  },
  load: false
})

// 响应处理
request.dataFactory = (response: IAxiosResponse) => {
  if (response.status === 200 && response.data) {
    const { code, data, message } = response.data
    if (code === 0) {
      return data
    } else {
      ElMessage.error(message)
      return Promise.reject(response.data)
    }
  }
  Promise.reject({ message: ErrMessageInfo.errorMessage })
}

// 异常处理
request.requestError = (error: AxiosError) => {
  // console.error(`【接口异常： 】`, error)
  const { response, code, message } = error || {}
  if (code === 'ECONNABORTED' && message.indexOf('timeout') !== -1) {
    return { message: ErrMessageInfo.apiTimeoutMessage }
  }
  if (code === 'ERR_CANCELED') {
    return Promise.resolve({
      code,
      message: ErrMessageInfo.canceledError
    })
  }
  if (response) {
    const errMessage = checkStatus(response.status)
    if (errMessage) {
      return Promise.reject({
        code: response.status,
        message: errMessage
      })
    }
  }
  Promise.reject({ message: ErrMessageInfo.errorMessage })
}

function checkStatus(code: any) {
  let errMessage
  switch (code) {
    case 400:
      errMessage = ErrMessageInfo.errMsg401
      break
    // 401: Not logged in
    case 401:
      // token
      errMessage = ErrMessageInfo.errMsg401
      break
    case 403:
      errMessage = ErrMessageInfo.errMsg403
      break
    case 404:
      errMessage = ErrMessageInfo.errMsg404
      break
    case 405:
      errMessage = ErrMessageInfo.errMsg405
      break
    case 408:
      errMessage = ErrMessageInfo.errMsg408
      break
    case 500:
      errMessage = ErrMessageInfo.errMsg500
      break
    case 501:
      errMessage = ErrMessageInfo.errMsg501
      break
    case 502:
      errMessage = ErrMessageInfo.errMsg502
      break
    case 503:
      errMessage = ErrMessageInfo.errMsg503
      break
    case 504:
      errMessage = ErrMessageInfo.errMsg504
      break
    case 505:
      errMessage = ErrMessageInfo.errMsg505
      break
    default:
  }
  return errMessage
}

export default () => {}
export { request }
